﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Script.Serialization;
using Warehouse.Web.AppCode;

namespace Warehouse.Web.Sales
{
    public partial class BillHistory : BasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                base.RegisterClientScriptContent("alldistributor", new JavaScriptSerializer().Serialize(DataAccess.Distributor.GetDistributors()));

                if (Request.QueryString.AllKeys.Contains("search"))
                {
                    DateTime dtStart = DateTime.Parse(Request.QueryString["Start"]);
                    DateTime dtEnd = DateTime.Parse(Request.QueryString["End"]);
                    this.tbStartDate.Text = dtStart.ToString("yyyy-MM-dd");
                    this.tbEndDate.Text = dtEnd.ToString("yyyy-MM-dd");

                    int distributorId = int.Parse(Request.QueryString["DistributorID"]);

                    var distributor = DataAccess.Distributor.GetOne(p => p.ID == distributorId);
                    if (distributor != null)
                    {
                        tbDistributor.Text = distributor.Name;
                    }
                    LoadData(distributorId, dtStart, dtEnd.AddDays(1));
                }
                else
                {
                    this.tbStartDate.Text = DateTime.Now.AddDays(1 - DateTime.Now.Day).ToString("yyyy-MM-dd"); ;
                    this.tbEndDate.Text = DateTime.Now.ToString("yyyy-MM-dd");
                }
            }
        }

        void LoadData(int distributorId, DateTime startDate, DateTime endDate)
        {
            var saleviews = DataAccess.CustomeEntity<DataAccess.SalesView>.GetList(p => p.DistributorID == distributorId && p.SalesDate >= startDate && p.SalesDate < endDate && p.Status == (int)DataAccess.BillStatus.Default).ToList();
            var paymentviews = DataAccess.CustomeEntity<DataAccess.ReceiptView>.GetList(p => p.DistributorID == distributorId && p.ReceiptDate >= startDate && p.ReceiptDate < endDate && p.Status == (int)DataAccess.BillStatus.Default).ToList();

            List<DataWrapper> datasource = new List<DataWrapper>();
            datasource.AddRange(saleviews.Select(p =>
             {
                 string op = string.Empty;
                 switch ((DataAccess.SalesBillType)p.Type)
                 {
                     case DataAccess.SalesBillType.Sales:
                         op = "销售";
                         break;
                     case Warehouse.DataAccess.SalesBillType.Gift:
                         op = "赠品";
                         break;
                     case Warehouse.DataAccess.SalesBillType.Return:
                         op = "退货";
                         break;
                 }
                 return new DataWrapper()
             {
                 Group = p.BillID.ToString(),
                 Date = p.SalesDate,
                 Summary = string.Format("{0}: {1} {2} {3} ({4})  {5}*{6}", op, p.Name, p.Grade, p.Model, p.Specification, p.Price, p.Count),
                 ShouldPay = (p.Type == (int)DataAccess.SalesBillType.Return ? -1 : 1) * p.Amount,
                 RealPay = 0,
                 Type = p.Type,
                 BillID = p.BillID,
                 CreateDate = p.CreateDate,
             };
             }));
            datasource.AddRange(paymentviews.Select(p =>
            {
                var d = new DataWrapper()
                 {
                     Group = ("P_" + p.BillID.ToString()),
                     Date = p.ReceiptDate,
                     Summary = string.Format("【{0}】 {1} {2:C2}", p.AccountName, p.IsExpense ? "付款" : "收款", p.Amount),
                     ShouldPay = 0,
                     RealPay = (p.IsExpense ? -1 : 1) * p.Amount,
                     BillID = p.BillID,
                     Type = p.IsExpense ? -2 : -1,
                     CreateDate = p.CreateDate
                 };
                if (p.SalesBillID.HasValue)
                {
                    var saleBill = saleviews.FirstOrDefault(arg => arg.BillID == p.SalesBillID.Value);
                    d.Group = p.SalesBillID.Value.ToString();
                    d.BillID = p.SalesBillID.Value;
                    d.Type = saleBill.Type;
                    d.CreateDate = saleBill.CreateDate;
                }
                return d;
            }));
            datasource = (from t in datasource orderby t.Date, t.CreateDate select t).ToList();


            double toalOverage = 0;
            string lastGroup = string.Empty;
            datasource.Insert(0, new DataWrapper()
            {
                Date = startDate,
                Summary = "",
                ShouldPay = 0,
                RealPay = 0,
                Overage = toalOverage = DataAccess.SalesView.GetShouldPay(distributorId, startDate) - DataAccess.PaymentView.GetPaidAmount(distributorId, startDate),
                CreateDate = startDate
            });
            foreach (var d in datasource)
            {
                d.Overage = toalOverage = toalOverage + d.ShouldPay - d.RealPay;
                if (string.Compare(lastGroup, d.Group) != 0)
                {
                    d.DateStr = d.Date.ToString("yyyy-MM-dd");
                    lastGroup = d.Group;
                }
            }

            this.rptData.DataSource = datasource;
            this.rptData.DataBind();
        }

        class DataWrapper
        {
            public string Group { get; set; }
            public DateTime Date { get; set; }
            public string Summary { get; set; }
            public double ShouldPay { get; set; }
            public double RealPay { get; set; }
            public double Overage { get; set; }
            public int Type { get; set; }
            public Guid BillID { get; set; }
            public DateTime CreateDate { get; set; }

            public string DateStr { get; set; }
            public string RealPayStr { get { return this.RealPay == 0 ? "" : this.RealPay.ToString("#,##0.00"); } }
            public string ShouldPayStr { get { return this.ShouldPay == 0 ? "" : this.ShouldPay.ToString("#,##0.00"); } }
        }
    }
}
